<template>
  <div class="dashboard">
    <div class="header">
      <div class="logo">
        <h1>振为鑫</h1>
      </div>
      <h1 class="title">历史客户数据仪表盘</h1>
    </div>
    
    <!-- 添加搜索框 -->
    <div class="search-container">
      <input 
        type="text" 
        v-model="searchQuery" 
        placeholder="搜索客户..." 
        class="search-input"
        @keyup.enter="searchCustomers"
      />
      <button class="search-button" @click="searchCustomers">搜索</button>
    </div>
    
    <div class="stats-cards">
      <stat-card 
        title="总客户量" 
        :value="totalCustomers" 
        color="#4B7BEC"
        :is-customer-count="true"
      />
      <stat-card 
        title="平台种类" 
        :value="platformCount" 
        color="#45AAF2"
        :is-customer-count="true"
      />
    
    
    </div>
    
    <div class="charts-container">
      <div class="chart-box">
        <h3>平台标签饼图</h3>
        <div class="chart" ref="platformPieChart"></div>
      </div>
      
      <div class="chart-box">
        <h3>销售阶段柱形图</h3>
        <div class="chart" ref="salesStageChart"></div>
      </div>
      
      <div class="chart-box">
        <h3>平台标签柱形图</h3>
        <div class="chart" ref="platformBarChart"></div>
      </div>
      <!-- 新增：每月新增客户柱状图 -->
      <div class="chart-box monthly-bar-box">
        <h3>每月新增沟通客户量</h3>
        <div class="chart monthly-bar-chart" ref="monthlyCustomersChart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import api from '../services/api';
import StatCard from '../components/StatCard.vue';

export default {
  components: {
    StatCard
  },
  setup() {
    const router = useRouter();
    const salesStageChart = ref(null);
    const platformPieChart = ref(null);
    const platformBarChart = ref(null);
    const searchQuery = ref(''); // 搜索查询
    
    const customers = ref([]);
    const salesStageStats = ref([]);
    const platformStats = ref([]);
    const monthlyCustomersStats = ref([]);
    const monthlyCustomersChart = ref(null);
    
    // 计算总客户数量
    const totalCustomers = computed(() => {
      // 后端已经进行了客户去重，直接使用销售阶段统计数据的总和
      return salesStageStats.value.reduce((total, stage) => total + stage.value, 0);
    });
    // 计算销售阶段数量
    const salesStageCount = computed(() => salesStageStats.value.length);
    // 计算平台数量 - 修正为实际平台数量
    const platformCount = computed(() => platformStats.value.length);
    
    // 假设总价和单价 (实际项目中这些应该来自API)
    const totalPrice = ref(0);
    const averagePrice = ref(0);
    
    // 搜索客户
    const searchCustomers = async () => {
      if (!searchQuery.value.trim()) return;
      
      try {
        // 跳转到详情页面，将搜索关键词作为参数传递
        router.push(`/detail/search?keyword=${encodeURIComponent(searchQuery.value)}`);
      } catch (error) {
        console.error('搜索客户出错:', error);
      }
    };
    
    const fetchData = async () => {
      try {
        const [customersRes, salesStageRes, platformRes, monthlyCustomersRes] = await Promise.all([
          api.getAllCustomers(),
          api.getSalesStageStats(),
          api.getPlatformStats(),
          api.getMonthlyCustomers()
        ]);
        
        // 处理客户数据
        if (customersRes.data) {
          customers.value = customersRes.data;
        }
        
        // 处理销售阶段统计
        if (salesStageRes.data) {
          salesStageStats.value = salesStageRes.data;
        }
        
        // 处理平台统计
        if (platformRes.data) {
          platformStats.value = platformRes.data;
        }
        
        // 新增：处理每月新增客户统计
        if (monthlyCustomersRes.data) {
          monthlyCustomersStats.value = monthlyCustomersRes.data;
        }
        
  
        
        initCharts();
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    
    const initCharts = () => {
      // 销售阶段柱状图
      if (salesStageChart.value) {
        const chart = echarts.init(salesStageChart.value);
        
        // 定义销售阶段分组
        const stageGroups = [
          ["破冰与产品介绍", ["破冰", "破冰/产品营销", "产品营销"]],
          ["价格谈判与异议", ["价格谈判", "价格谈判/处理客户异议", "处理客户异议"]],
          ["逼单", ["逼单"]],  // 单独列出逼单环节
          ["成交与售后", ["成交", "成交/售后", "售后"]]  // 合并剩余成交和售后相关项
        ];
        
        // 合并销售阶段数据
        const mergedStageStats = [];
        stageGroups.forEach(([groupName, stages]) => {
          const totalValue = salesStageStats.value
            .filter(item => stages.includes(item.name))
            .reduce((sum, item) => sum + item.value, 0);
          
          mergedStageStats.push({
            name: groupName,
            value: totalValue
          });
        });
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: mergedStageStats.map(item => item.name),
            axisLine: {
              lineStyle: {
                color: '#8C9EFF'
              }
            },
            axisLabel: {
              color: '#fff'
            }
          },
          yAxis: {
            type: 'value',
            axisLine: {
              lineStyle: {
                color: '#8C9EFF'
              }
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(140, 158, 255, 0.2)'
              }
            },
            axisLabel: {
              color: '#fff'
            }
          },
          series: [
            {
              name: '客户数量',
              type: 'bar',
              barWidth: '60%',
              data: mergedStageStats.map(item => item.value),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#9F44D3' },
                  { offset: 1, color: '#7A88FF' }
                ])
              }
            }
          ]
        };
        
        chart.setOption(option);
        
        chart.on('click', function(params) {
          // 点击合并后的销售阶段，需要找到对应的原始阶段
          const groupName = params.name;
          const group = stageGroups.find(group => group[0] === groupName);
          
          if (group) {
            // 创建一个查询参数，包含所有相关的原始阶段
            const stagesParam = encodeURIComponent(JSON.stringify(group[1]));
            // 跳转到一个新的路由，这个路由将处理多个阶段的情况
            router.push(`/detail/sales_stages?stages=${stagesParam}`);
          }
        });
        
        window.addEventListener('resize', () => {
          chart.resize();
        });
      }
      
      // 平台标签饼图
      if (platformPieChart.value) {
        const chart = echarts.init(platformPieChart.value);
        
        const option = {
          tooltip: {
            trigger: 'item'
          },
          series: [
            {
              name: '平台分布',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#1E1E2E',
                borderWidth: 2
              },
              label: {
                show: true,
                position: 'outside',
                color: '#fff',
                formatter: '{b}: {c}'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: true,
                lineStyle: {
                  color: '#8C9EFF'
                }
              },
              data: platformStats.value,
              color: ['#9F44D3', '#7A88FF', '#45AAF2', '#2E86DE', '#8C7AE6', '#3867D6']
            }
          ]
        };
        
        chart.setOption(option);
        
        chart.on('click', function(params) {
          router.push(`/detail/platform/${params.name}`);
        });
        
        window.addEventListener('resize', () => {
          chart.resize();
        });
      }
      
      // 平台标签柱状图
      if (platformBarChart.value) {
        const chart = echarts.init(platformBarChart.value);
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: platformStats.value.map(item => item.name),
            axisLine: {
              lineStyle: {
                color: '#8C9EFF'
              }
            },
            axisLabel: {
              color: '#fff'
            }
          },
          yAxis: {
            type: 'value',
            axisLine: {
              lineStyle: {
                color: '#8C9EFF'
              }
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(140, 158, 255, 0.2)'
              }
            },
            axisLabel: {
              color: '#fff'
            }
          },
          series: [
            {
              name: '客户数量',
              type: 'bar',
              barWidth: '60%',
              data: platformStats.value.map(item => item.value),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#4B7BEC' },
                  { offset: 1, color: '#3867D6' }
                ])
              }
            }
          ]
        };
        
        chart.setOption(option);
        
        chart.on('click', function(params) {
          router.push(`/detail/platform/${params.name}`);
        });
        
        window.addEventListener('resize', () => {
          chart.resize();
        });
      }

      // 新增：每月新增客户柱状图
      if (monthlyCustomersChart.value) {
        const chart = echarts.init(monthlyCustomersChart.value);
        const months = monthlyCustomersStats.value.map(item => item.month); // 保持后端顺序
        const values = monthlyCustomersStats.value.map(item => item.value);
        // 计算默认显示的柱子数量
        const showCount = 6;
        const totalCount = months.length;
        const startPercent = totalCount > showCount ? 100 - (showCount / totalCount) * 100 : 0;
        const option = {
          title: { text: '', left: 'center', textStyle: { color: '#fff', fontSize: 16 } },
          tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
          grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
          xAxis: {
            type: 'category',
            data: months,
            axisLine: { lineStyle: { color: '#8C9EFF' } },
            axisLabel: { color: '#fff', rotate: 0 },
          },
          yAxis: {
            type: 'value',
            axisLine: { lineStyle: { color: '#8C9EFF' } },
            splitLine: { lineStyle: { color: 'rgba(140, 158, 255, 0.2)' } },
            axisLabel: { color: '#fff' },
          },
          dataZoom: [
            { type: 'slider', show: true, xAxisIndex: 0, height: 16, bottom: 0, start: startPercent, end: 100, handleSize: 0, backgroundColor: 'rgba(0,0,0,0)', borderColor: 'rgba(0,0,0,0)' }
          ],
          series: [
            {
              name: '新增客户量',
              type: 'bar',
              barWidth: '60%',
              data: values,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#45AAF2' },
                  { offset: 1, color: '#3867D6' }
                ])
              }
            }
          ]
        };
        chart.setOption(option);
        window.addEventListener('resize', () => { chart.resize(); });
        // 新增：点击跳转到详情
        chart.on('click', function(params) {
          if (params.name) {
            router.push(`/detail/month?month=${params.name}`);
          }
        });
      }
    };

    onMounted(() => {
      fetchData();  // 获取数据
    });
    
    return {
      salesStageChart,
      platformPieChart,
      platformBarChart,
      monthlyCustomersChart,
      totalCustomers,
      salesStageCount,
      platformCount,
      totalPrice,
      averagePrice,
      searchQuery,
      searchCustomers,
      monthlyCustomersStats
    };
  }
};
</script>

<style scoped>
.dashboard {
  background-color: #1E1E2E;
  color: #fff;
  min-height: 100vh;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.logo {
  display: flex;
  align-items: center;
}

.logo img {
  height: 40px;
  margin-right: 10px;
}

.search-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  width: 100%;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border-radius: 5px 0 0 5px;
  border: none;
  background-color: #282A42;
  color: #fff;
  font-size: 16px;
}

.search-input::placeholder {
  color: #8C9EFF;
}

.search-button {
  background-color: #4B7BEC;
  color: #fff;
  border: none;
  padding: 10px 20px;
  border-radius: 0 5px 5px 0;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.search-button:hover {
  background-color: #3867D6;
}

.stats-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.chart-box {
  background-color: #282A42;
  border-radius: 10px;
  padding: 15px;
}

.chart-box h3 {
  margin-top: 0;
  color: #fff;
  font-size: 16px;
}

.chart {
  height: 300px;
}

.monthly-bar-box {
  grid-column: 1 / -1;
  overflow-x: auto;
}
.monthly-bar-chart {
  min-width: 600px;
  height: 300px;
}
</style> 